import warnings
warnings.warn("qturboframe.public_ui.ucf_h_ui.select_tree模块已被废弃，替代模块为qturboframe.public_ui.h_ui.select_tree", DeprecationWarning)

from time import sleep

from qturboframe.lib.report.log import logger
from qturboframe.lib.ranorex.exceptions import CsClientError
from qturboframe.lib.ranorex.web_element.div_tag import DivTag
from qturboframe.lib.ranorex.web_element.ul_tag import UlTag
from qturboframe.lib.ranorex.web_element.li_tag import LiTag
from qturboframe.lib.ranorex.web_element.span_tag import SpanTag
from qturboframe.lib.ranorex.web_element.i_tag import ITag
from qturboframe.lib.utils.check import CheckBasic
from ..ucf_base_element import BaseElement
from .tree import Tree


class SelectTree(BaseElement, CheckBasic):
    '''hui下拉树框控件操作'''

    def __init__(self, element_para, father=None, timeout=10000):
        super().__init__(element_para, father, timeout)
        class_list = self._element.get_attribute('class').split(' ')
        if 'h-selectTree' not in class_list:
            self._element = self._element.find_element_by_attribute(
                'xpath', './ancestor::div[@class~\'h-selectTree\']', timeout=self.timeout)
        self._element = DivTag(self._element.control)

    def set_value_for_single(self, value, timeout=20000):
        """
        hui单选下拉树形框选择

        :Args:
         - value: 选择项的节点，例：XX1/XX2/XX3
         - timeout: 超时时间，默认是20s

        :Example:
         - 例: select_tree.set_value_for_single('根节点/子节点/叶子节点')
        """
        loading_ul_class = r'h-selectTree-loading'
        DivTag(self._element.find_element_by_attribute(
            'xpath', './/div[@class~\'h-selectTree-selection\']').control).secure_click()
        select_div = self._element.exist(
            'xpath', './/div[@class~\'h-select-dropdown\']', timeout=100)
        if not select_div:
            select_div = self._driver.find_element_by_attribute(
                'xpath', './body/div[@class~\'h-select-dropdown\']', 'style:display: block;',
                timeout=self.timeout)
        select_div = DivTag(select_div.control)
        timeout1 = 0
        while timeout1 < timeout * 10:
            loading_ul = select_div.exist(
                'xpath', './/ul[@class~\'{}\']'.format(loading_ul_class), timeout=self.timeout)
            if loading_ul:
                loading_ul = UlTag(loading_ul.control)
            if not loading_ul.is_displayed():
                break
            timeout1 += 1000
            sleep(0.1)
        else:
            raise CsClientError('树形下拉框中没有数据！')
        tree = Tree({'xpath': './/ul[@class~\'h-tree\']'}, select_div, self.timeout)
        tree.set_value_for_single(value)

    def set_value_for_multiple(self, value=['all'], timeout=20000):
        """
        hui的多选下拉树形框选择

        :Args:
         - value: 选择项的文本集合，例：[XX1/XX2/XX3, XX1/XX4/XX5]
         - timeout: 超时时间，默认是20s

        :Example:
         - 例: select_tree.set_value_for_multiple(['根节点1/子节点1/叶子节点1','根节点2/子节点2/叶子节点2'])
        """
        select_ul_class = r'h-selectTree-dropdown-list'
        # 先全部清空
        self.clear_for_multiple()
        # 弹出下拉框
        DivTag(self._element.find_element_by_attribute(
            'xpath', './/div[@class~\'h-selectTree-selection\']',
            timeout=self.timeout).control).secure_click()
        select_div = self._element.exist(
            'xpath', './/div[@class~\'h-select-dropdown\']', timeout=100)
        if not select_div:
            select_div = self._driver.find_element_by_attribute(
                'xpath', './body/div[@class~\'h-select-dropdown\']', 'style:display: block;',
                timeout=self.timeout)
        select_div = DivTag(select_div.control)
        timeout1 = 0
        while timeout1 < timeout * 10:
            select_ul = select_div.exist(
                'xpath', './/div[@class~\'{}\']'.format(select_ul_class), timeout=self.timeout)
            if select_ul:
                select_ul = DivTag(select_ul.control)
            if select_ul.is_displayed():
                break
            timeout1 += 1000
            sleep(0.1)
        else:
            raise CsClientError('树形下拉框中没有数据！')
        if len(value) == 1 and value[0] == 'all':
            select_lis = [LiTag(webelement.control) for webelement in
                          select_ul.find_elements_by_attribute('xpath', './/li', timeout=self.timeout)]
            for li in select_lis:
                SpanTag(li.find_element_by_attribute(
                    'xpath', './/span[@class~\'h-checkbox\']',
                    timeout=self.timeout).control).secure_click()
        else:
            tree = Tree({'xpath': './/ul[@class~\'h-tree\']'}, select_div, self.timeout)
            tree.set_value_for_multiple(value)

    def is_default(self, value):
        """
        检查hui下拉树形框默认值

        :Args:
         - value: 待检查的选项值

        :Returns:
            匹配返回True，否则返回False

        :Example:
         - 例1: select_tree.is_default('节点1,节点2')
         - 例2: select_tree.is_default('节点1')
        """
        select_div = DivTag(self._element.find_element_by_attribute(
            'xpath', './/div[@class~\'h-selectTree-selection\']', timeout=self.timeout).control)
        title = select_div.get_attribute('title')
        if title:
            if value == title:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        span_default = select_div.exist(
            'xpath', './/span[@class~\'h-selectTree-placeholder\']', timeout=self.timeout)
        if span_default and span_default.is_displayed():
            span_default = SpanTag(span_default.control)
            text = span_default.text
            if value == text:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        else:
            logger.error('没有默认值！')
            return False

    def is_nonnull(self):
        '''
        检查hui下拉树形框是否有非空属性

        :Returns:
            非空返回True，否则返回False

        :Example:
         - 例: select_tree.is_nonnull()
        '''
        self._element.focus()
        form_item = DivTag(self._element.find_element_by_attribute(
            'xpath', './ancestor::div[@class~\'h-form-item-content\']/'
                     'parent::div[@class~\'h-form-item\']', timeout=self.timeout).control)
        item_class_list = form_item.get_attribute('class').split(' ')
        if 'h-form-item-required' in item_class_list:
            return True
        else:
            return False

    def clear_for_single(self):
        """
        hui单选树形下拉框清除选项值

        :Example:
         - 例: select_tree.clear_for_single()
        """
        self._element.move_to()
        clear_i = ITag(self._element.find_element_by_attribute(
            'xpath', './/div[@class~\'h-selectTree-selection\']/i[@class~\'h-icon-close\']',
            timeout=self.timeout).control)
        if clear_i.is_displayed():
            clear_i.secure_click()

    def clear_for_multiple(self):
        """
        hui多选树形下拉框清除选项值

        :Example:
         - 例: select_tree.clear_for_multiple()
        """
        self._element.move_to()
        clear_i = ITag(self._element.find_element_by_attribute(
            'xpath', './/div[@class~\'h-selectTree-selection\']/i[@class~\'h-icon-close\']',
            timeout=self.timeout).control)
        if clear_i.is_displayed():
            clear_i.secure_click()

    def check_default(self, value):
        """
        校验hui下拉树形框默认值

        :Args:
         - value: 待检查的选项值

        :Raises:
            匹配返回True，否则返回False

        :Example:
         - 例1: select_tree.check_default('节点1,节点2')
         - 例2: select_tree.check_default('节点1')
        """
        if not self.is_default(value):
            raise CsClientError('下拉树形框的默认值校验不通过！')

    def check_nonnull(self):
        '''
        校验hui下拉树形框是否有非空属性

        :Returns:
            非空返回True，否则返回False

        :Example:
         - 例: select_tree.check_nonnull()
        '''
        if not self.is_nonnull():
            raise CsClientError('下拉树形框的非空校验不通过！')
